<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="时间范围" prop="dateRange">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          @change="handleDateChange">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="loadData">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 核心指标卡片 -->
    <el-row :gutter="20" class="mb20">
      <el-col :span="6">
        <div class="metric-card">
          <div class="metric-icon">
            <i class="el-icon-s-order" style="color: #409EFF;"></i>
          </div>
          <div class="metric-content">
            <div class="metric-value">{{ formatNumber(metricsData.total_orders) }}</div>
            <div class="metric-label">总订单数</div>
            <div class="metric-trend" v-if="metricsData.order_trend">
              <span :class="metricsData.order_trend > 0 ? 'trend-up' : 'trend-down'">
                {{ metricsData.order_trend > 0 ? '↑' : '↓' }} {{ Math.abs(metricsData.order_trend) }}%
              </span>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="metric-card">
          <div class="metric-icon">
            <i class="el-icon-money" style="color: #67C23A;"></i>
          </div>
          <div class="metric-content">
            <div class="metric-value">¥{{ formatNumber(metricsData.total_order_amount) }}</div>
            <div class="metric-label">订单总金额</div>
            <div class="metric-trend" v-if="metricsData.amount_trend">
              <span :class="metricsData.amount_trend > 0 ? 'trend-up' : 'trend-down'">
                {{ metricsData.amount_trend > 0 ? '↑' : '↓' }} {{ Math.abs(metricsData.amount_trend) }}%
              </span>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="metric-card">
          <div class="metric-icon">
            <i class="el-icon-success" style="color: #E6A23C;"></i>
          </div>
          <div class="metric-content">
            <div class="metric-value">¥{{ formatNumber(metricsData.total_pay_amount) }}</div>
            <div class="metric-label">已支付金额</div>
            <div class="metric-trend" v-if="metricsData.paid_trend">
              <span :class="metricsData.paid_trend > 0 ? 'trend-up' : 'trend-down'">
                {{ metricsData.paid_trend > 0 ? '↑' : '↓' }} {{ Math.abs(metricsData.paid_trend) }}%
              </span>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="metric-card">
          <div class="metric-icon">
            <i class="el-icon-pie-chart" style="color: #F56C6C;"></i>
          </div>
          <div class="metric-content">
            <div class="metric-value">{{ metricsData.payment_rate }}%</div>
            <div class="metric-label">支付转化率</div>
            <div class="metric-trend" v-if="metricsData.conversion_trend">
              <span :class="metricsData.conversion_trend > 0 ? 'trend-up' : 'trend-down'">
                {{ metricsData.conversion_trend > 0 ? '↑' : '↓' }} {{ Math.abs(metricsData.conversion_trend) }}%
              </span>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 状态分布图表 -->
    <el-row :gutter="20" class="mb20">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>支付状态分布</span>
          </div>
          <div id="paymentStatusChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>订单金额分布</span>
          </div>
          <div id="orderAmountChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 转化漏斗图表 -->
    <el-row :gutter="20" class="mb20">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>订单转化漏斗</span>
            <el-tooltip
              content="转化漏斗反映用户从浏览商品到最终确认收货的转化过程，包含浏览商品→加入购物车→提交订单→支付订单→确认收货五个关键环节，帮助分析各环节的转化率和流失情况"
              placement="top"
              effect="dark">
              <i class="el-icon-question" style="margin-left: 8px; color: #909399; cursor: pointer;"></i>
            </el-tooltip>
          </div>
          <div id="funnelChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>订单趋势分析</span>
            <el-radio-group v-model="trendTimeType" size="mini" style="float: right;" @change="loadTrendData">
              <el-radio-button label="day">按天</el-radio-button>
              <el-radio-button label="week">按周</el-radio-button>
              <el-radio-button label="month">按月</el-radio-button>
            </el-radio-group>
          </div>
          <div id="trendChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 订单详情表格 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>订单详情列表</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="exportData">导出数据</el-button>
      </div>

      <!-- 订单列表筛选条件 -->
      <el-form :model="orderQueryParams" ref="orderQueryForm" size="small" :inline="true" label-width="80px" class="mb20">
        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="orderQueryParams.userName"
            placeholder="请输入用户名称"
            clearable
            size="small"
            style="width: 150px"
            @keyup.enter.native="handleOrderQuery"
          />
        </el-form-item>
        <el-form-item label="下单时间" prop="orderTimeRange">
          <el-date-picker
            v-model="orderQueryParams.orderTimeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            size="small"
            style="width: 320px"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单金额" prop="totalAmountRange">
          <el-input
            v-model="orderQueryParams.minTotalAmount"
            placeholder="最小金额"
            size="small"
            style="width: 100px"
            type="number"
          />
          <span style="margin: 0 5px;">至</span>
          <el-input
            v-model="orderQueryParams.maxTotalAmount"
            placeholder="最大金额"
            size="small"
            style="width: 100px"
            type="number"
          />
        </el-form-item>
        <el-form-item label="支付金额" prop="paymentAmountRange">
          <el-input
            v-model="orderQueryParams.minPaymentAmount"
            placeholder="最小金额"
            size="small"
            style="width: 100px"
            type="number"
          />
          <span style="margin: 0 5px;">至</span>
          <el-input
            v-model="orderQueryParams.maxPaymentAmount"
            placeholder="最大金额"
            size="small"
            style="width: 100px"
            type="number"
          />
        </el-form-item>
        <el-form-item label="支付状态" prop="paymentStatus">
          <el-select v-model="orderQueryParams.paymentStatus" placeholder="请选择支付状态" clearable size="small" style="width: 120px">
            <el-option label="待支付" value="待支付"></el-option>
            <el-option label="待发货" value="待发货"></el-option>
            <el-option label="待收货" value="待收货"></el-option>
            <el-option label="已完成" value="已完成"></el-option>
            <el-option label="已取消" value="已取消"></el-option>
            <el-option label="已退款" value="已退款"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleOrderQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetOrderQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="tableLoading"
        :data="orderList"
        border
        stripe
        style="width: 100%"
        header-align="center"
        :show-summary="true"
        :summary-method="getSummaries">
        <el-table-column prop="order_no" label="订单号" min-width="160" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column prop="user_name" label="用户名称" min-width="120" show-overflow-tooltip align="center"></el-table-column>
        <el-table-column prop="order_time" label="下单时间" min-width="160" align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.order_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="total_amount" label="订单金额" min-width="120" align="center">
          <template slot-scope="scope">
            ¥{{ formatNumber(scope.row.total_amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="payment_amount" label="支付金额" min-width="120" align="center">
          <template slot-scope="scope">
            ¥{{ formatNumber(scope.row.payment_amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="payment_status" label="支付状态" min-width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.payment_status)" size="mini">
              {{ scope.row.payment_status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="product_quantity" label="商品件数" min-width="100" align="center"></el-table-column>
      </el-table>

      <pagination
        v-show="pagination.total > 0"
        :total="pagination.total"
        :page.sync="pagination.pageNum"
        :limit.sync="pagination.pageSize"
        @pagination="loadOrderDetails" />
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getOrderMetrics, getOrderDetails, getOrderFunnelData, getOrderTrendData, getOrderAmountDistribution, exportOrderData } from '@/api/statistics/order'

export default {
  name: 'OrderAnalyse',
  data() {
    return {
      // 查询参数
      queryParams: {},
      showSearch: true,
      dateRange: [],

      // 订单列表筛选参数
      orderQueryParams: {
        userName: '',
        orderTimeRange: [],
        minTotalAmount: '',
        maxTotalAmount: '',
        minPaymentAmount: '',
        maxPaymentAmount: '',
        paymentStatus: ''
      },

      // 核心指标数据
      metricsData: {
        total_orders: 0,
        total_order_amount: 0,
        total_pay_amount: 0,
        payment_rate: 0,
        order_trend: 0,
        amount_trend: 0,
        paid_trend: 0,
        conversion_trend: 0
      },

      // 订单列表数据
      orderList: [],
      tableLoading: false,

      // 分页信息
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },

      // 图表相关
      trendTimeType: 'day',// 图表实例
      paymentStatusChart: null,
      orderAmountChart: null,
      funnelChart: null,
      trendChart: null
    }
  },

  mounted() {
    this.initDateRange()
    this.loadData()
  },

  beforeDestroy() {
    // 销毁图表实例
    if (this.paymentStatusChart) {
      this.paymentStatusChart.dispose()
    }
    if (this.orderAmountChart) {
      this.orderAmountChart.dispose()
    }
    if (this.funnelChart) {
      this.funnelChart.dispose()
    }
    if (this.trendChart) {
      this.trendChart.dispose()
    }
  },

  methods: {
    // 初始化日期范围（默认最近30天）
    initDateRange() {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 30 * 24 * 60 * 60 * 1000)
      this.dateRange = [this.formatDate(start, 'yyyy-MM-dd'), this.formatDate(end, 'yyyy-MM-dd')]
    },

    // 处理日期变化
    handleDateChange(val) {
      this.dateRange = val
    },

    // 重置查询
    resetQuery() {
      this.initDateRange()
      this.loadData()
    },

    // 加载所有数据
    async loadData() {
      await Promise.all([
        this.loadMetrics(),
        this.loadOrderDetails(),
        this.loadFunnelData(),
        this.loadTrendData(),
        this.loadStatusDistribution()
      ])
    },

    // 加载核心指标
    async loadMetrics() {
      try {
        const params = {
          startDate: this.dateRange[0],
          endDate: this.dateRange[1]
        }
        const response = await getOrderMetrics(params)
        if (response.code === 200) {
          const data = response.data || {}
          // 处理核心指标数据
          if (data.metrics) {
            this.metricsData = {
              total_orders: data.metrics.total_orders || 0,
              total_order_amount: data.metrics.total_order_amount || 0,
              total_pay_amount: data.metrics.total_pay_amount || 0,
              payment_rate: data.metrics.payment_rate || 0,
              order_trend: 0, // 趋势数据需要单独计算
              amount_trend: 0,
              paid_trend: 0,
              conversion_trend: 0
            }
          }
        }
      } catch (error) {
        console.error('加载核心指标失败:', error)
        this.$message.error('加载核心指标失败')
      }
    },

    // 加载订单详情列表
    async loadOrderDetails() {
      this.tableLoading = true
      try {
        const params = {
          pageNum: this.pagination.pageNum,
          pageSize: this.pagination.pageSize,
          startDate: this.dateRange[0],
          endDate: this.dateRange[1]
        }

        // 添加筛选条件（只添加非空值）
        if (this.orderQueryParams.userName && this.orderQueryParams.userName.trim()) {
          params.userName = this.orderQueryParams.userName.trim()
        }
        if (this.orderQueryParams.orderTimeRange && this.orderQueryParams.orderTimeRange.length === 2) {
          params.orderStartTime = this.orderQueryParams.orderTimeRange[0]
          params.orderEndTime = this.orderQueryParams.orderTimeRange[1]
        }
        if (this.orderQueryParams.minTotalAmount && this.orderQueryParams.minTotalAmount.toString().trim()) {
          params.minTotalAmount = this.orderQueryParams.minTotalAmount.toString().trim()
        }
        if (this.orderQueryParams.maxTotalAmount && this.orderQueryParams.maxTotalAmount.toString().trim()) {
          params.maxTotalAmount = this.orderQueryParams.maxTotalAmount.toString().trim()
        }
        if (this.orderQueryParams.minPaymentAmount && this.orderQueryParams.minPaymentAmount.toString().trim()) {
          params.minPaymentAmount = this.orderQueryParams.minPaymentAmount.toString().trim()
        }
        if (this.orderQueryParams.maxPaymentAmount && this.orderQueryParams.maxPaymentAmount.toString().trim()) {
          params.maxPaymentAmount = this.orderQueryParams.maxPaymentAmount.toString().trim()
        }
        if (this.orderQueryParams.paymentStatus && this.orderQueryParams.paymentStatus.trim()) {
          params.paymentStatus = this.orderQueryParams.paymentStatus.trim()
        }

        console.log('发送订单详情请求:', params)
        const response = await getOrderDetails(params)
        console.log('订单详情响应:', response)

        if (response.code === 200) {
          // 处理响应数据，确保正确解析
          const data = response.data || {}
          this.orderList = data.rows || []
          this.pagination.total = data.total || 0

          console.log('订单列表数据:', this.orderList)
          console.log('总数:', this.pagination.total)
        } else {
          this.$message.error('获取订单详情失败: ' + (response.msg || '未知错误'))
          this.orderList = []
          this.pagination.total = 0
        }
      } catch (error) {
        console.error('加载订单详情失败:', error)
        this.$message.error('加载订单详情失败')
        this.orderList = []
        this.pagination.total = 0
      } finally {
        this.tableLoading = false
      }
    },

    // 加载转化漏斗数据
    async loadFunnelData() {
      try {
        const params = {
          startDate: this.dateRange[0],
          endDate: this.dateRange[1]
        }
        const response = await getOrderFunnelData(params)
        if (response.code === 200) {
          this.renderFunnelChart(response.data || [])
        }
      } catch (error) {
        console.error('加载转化漏斗数据失败:', error)
      }
    },

    // 加载趋势数据
    async loadTrendData() {
      try {
        const params = {
          startDate: this.dateRange[0],
          endDate: this.dateRange[1],
          timeType: this.trendTimeType
        }
        const response = await getOrderTrendData(params)
        if (response.code === 200) {
          this.renderTrendChart(response.data || [])
        }
      } catch (error) {
        console.error('加载趋势数据失败:', error)
      }
    },

    // 加载状态分布数据
    async loadStatusDistribution() {
      // 使用核心指标数据中的状态分布信息
      try {
        const params = {
          startDate: this.dateRange[0],
          endDate: this.dateRange[1]
        }
        const response = await getOrderMetrics(params)
        if (response.code === 200 && response.data) {
          // 基于实际数据计算状态分布
          const metrics = response.data.metrics || {}
          const paymentStatus = [
            { name: '已支付', value: metrics.paid_orders || 0 },
            { name: '待支付', value: metrics.pending_payment_orders || 0 },
            { name: '已退款', value: metrics.refund_orders || 0 }
          ]

          this.renderPaymentStatusChart(paymentStatus)
        }

        // 获取订单金额分布数据
        const amountResponse = await getOrderAmountDistribution(params)
        if (amountResponse.code === 200 && amountResponse.data) {
          this.renderOrderAmountChart(amountResponse.data)
        } else {
          // 使用默认数据
          this.renderOrderAmountChart([
            { name: '0-100元', value: 25 },
            { name: '100-500元', value: 35 },
            { name: '500-1000元', value: 25 },
            { name: '1000-2000元', value: 10 },
            { name: '2000元以上', value: 5 }
          ])
        }
      } catch (error) {
        console.error('加载状态分布数据失败:', error)
        // 使用模拟数据
        this.renderPaymentStatusChart([
          { name: '已支付', value: 65 },
          { name: '未支付', value: 25 },
          { name: '已取消', value: 10 }
        ])

        this.renderOrderAmountChart([
          { name: '0-100元', value: 30 },
          { name: '100-500元', value: 45 },
          { name: '500-1000元', value: 20 },
          { name: '1000-2000元', value: 3 },
          { name: '2000元以上', value: 2 }
        ])
      }
    },

    // 渲染支付状态分布图
    renderPaymentStatusChart(data) {
      this.$nextTick(() => {
        const chartDom = document.getElementById('paymentStatusChart')
        if (!chartDom) return

        if (this.paymentStatusChart) {
          this.paymentStatusChart.dispose()
        }

        this.paymentStatusChart = echarts.init(chartDom)
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: function(params) {
              return `${params.name}<br/>数量: ${params.value}<br/>占比: ${params.percent}%`
            }
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [
            {
              name: '支付状态',
              type: 'pie',
              radius: '50%',
              data: data,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }
        this.paymentStatusChart.setOption(option)
      })
    },

    // 渲染订单金额分布图
    renderOrderAmountChart(data) {
      this.$nextTick(() => {
        const chartDom = document.getElementById('orderAmountChart')
        if (!chartDom) return

        if (this.orderAmountChart) {
          this.orderAmountChart.dispose()
        }

        this.orderAmountChart = echarts.init(chartDom)
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: function(params) {
              return `${params.name}<br/>数量: ${params.value}<br/>占比: ${params.percent}%`
            }
          },
          legend: {
            orient: 'vertical',
            right: '10%',
            top: 'middle'
          },
          series: [
            {
              name: '订单金额分布',
              type: 'pie',
              radius: ['40%', '70%'],
              center: ['40%', '50%'],
              data: data,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              },
              label: {
                show: true,
                position: 'outside',
                formatter: '{b}: {c}%'
              }
            }
          ]
        }
        this.orderAmountChart.setOption(option)
      })
    },

    // 渲染转化漏斗图
    renderFunnelChart(data) {
      this.$nextTick(() => {
        const chartDom = document.getElementById('funnelChart')
        if (!chartDom) return

        if (this.funnelChart) {
          this.funnelChart.dispose()
        }

        this.funnelChart = echarts.init(chartDom)

        // 处理数据格式，确保value字段是数字
        const funnelData = data.map(item => ({
          name: item.stage || item.name,
          value: parseInt(item.value) || 0
        }))

        const option = {
          tooltip: {
            trigger: 'item',
            formatter: function(params) {
              return `${params.name}<br/>数量: ${params.value}<br/>占比: ${params.percent}%`
            }
          },
          series: [
            {
              name: '订单转化漏斗',
              type: 'funnel',
              left: '10%',
              top: 60,
              bottom: 60,
              width: '80%',
              min: 0,
              max: Math.max(...funnelData.map(item => item.value)),
              minSize: '0%',
              maxSize: '100%',
              sort: 'descending',
              gap: 2,
              label: {
                show: true,
                position: 'inside',
                formatter: '{b}: {c}'
              },
              labelLine: {
                length: 10,
                lineStyle: {
                  width: 1,
                  type: 'solid'
                }
              },
              itemStyle: {
                borderColor: '#fff',
                borderWidth: 1
              },
              emphasis: {
                label: {
                  fontSize: 16
                }
              },
              data: funnelData
            }
          ]
        }
        this.funnelChart.setOption(option)
      })
    },

    // 渲染趋势图
    renderTrendChart(data) {
      this.$nextTick(() => {
        const chartDom = document.getElementById('trendChart')
        if (!chartDom) return

        if (this.trendChart) {
          this.trendChart.dispose()
        }

        this.trendChart = echarts.init(chartDom)
        const dates = data.map(item => item.date_label || item.date)
        const orderCounts = data.map(item => item.order_count || 0)
        const amounts = data.map(item => item.total_amount || item.order_amount || 0)

        const option = {
          tooltip: {
            trigger: 'axis',
            formatter: function(params) {
              let result = params[0].name + '<br/>'
              params.forEach(param => {
                result += `${param.seriesName}: ${param.value}<br/>`
              })
              return result
            }
          },
          legend: {
            data: ['订单数量', '订单金额']
          },
          xAxis: {
            type: 'category',
            data: dates,
            axisLabel: {
              rotate: 45
            }
          },
          yAxis: [
            {
              type: 'value',
              name: '订单数量',
              position: 'left',
              axisLabel: {
                formatter: '{value}'
              }
            },
            {
              type: 'value',
              name: '订单金额',
              position: 'right',
              axisLabel: {
                formatter: '¥{value}'
              }
            }
          ],
          series: [
            {
              name: '订单数量',
              type: 'line',
              data: orderCounts,
              smooth: true,
              itemStyle: {
                color: '#409EFF'
              }
            },
            {
              name: '订单金额',
              type: 'line',
              yAxisIndex: 1,
              data: amounts,
              smooth: true,
              itemStyle: {
                color: '#67C23A'
              }
            }
          ]
        }
        this.trendChart.setOption(option)
      })
    },

    // 导出数据
    async exportData() {
      try {
        const params = {
          startDate: this.dateRange[0],
          endDate: this.dateRange[1]
        }

        // 添加筛选条件（只添加非空值）
        if (this.orderQueryParams.userName && this.orderQueryParams.userName.trim()) {
          params.userName = this.orderQueryParams.userName.trim()
        }
        if (this.orderQueryParams.orderTimeRange && this.orderQueryParams.orderTimeRange.length === 2) {
          params.orderStartTime = this.orderQueryParams.orderTimeRange[0]
          params.orderEndTime = this.orderQueryParams.orderTimeRange[1]
        }
        if (this.orderQueryParams.minTotalAmount && this.orderQueryParams.minTotalAmount.toString().trim()) {
          params.minTotalAmount = this.orderQueryParams.minTotalAmount.toString().trim()
        }
        if (this.orderQueryParams.maxTotalAmount && this.orderQueryParams.maxTotalAmount.toString().trim()) {
          params.maxTotalAmount = this.orderQueryParams.maxTotalAmount.toString().trim()
        }
        if (this.orderQueryParams.minPaymentAmount && this.orderQueryParams.minPaymentAmount.toString().trim()) {
          params.minPaymentAmount = this.orderQueryParams.minPaymentAmount.toString().trim()
        }
        if (this.orderQueryParams.maxPaymentAmount && this.orderQueryParams.maxPaymentAmount.toString().trim()) {
          params.maxPaymentAmount = this.orderQueryParams.maxPaymentAmount.toString().trim()
        }
        if (this.orderQueryParams.paymentStatus && this.orderQueryParams.paymentStatus.trim()) {
          params.paymentStatus = this.orderQueryParams.paymentStatus.trim()
        }

        // 创建下载链接
        const queryString = Object.keys(params).map(key => `${key}=${encodeURIComponent(params[key])}`).join('&')
        const downloadUrl = `/statistics/order/export?${queryString}`

        // 使用a标签下载文件
        const link = document.createElement('a')
        link.href = downloadUrl
        link.style.display = 'none'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)

        this.$message.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败')
      }
    },

    // 格式化数字
    formatNumber(num) {
      if (!num) return '0'
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    },

    // 格式化日期
    formatDate(date, format = 'yyyy-MM-dd HH:mm:ss') {
      if (!date) return ''
      if (typeof date === 'string') {
        date = new Date(date)
      }
      const o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'H+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds(),
        'q+': Math.floor((date.getMonth() + 3) / 3),
        'S': date.getMilliseconds()
      }
      if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
      }
      for (const k in o) {
        if (new RegExp('(' + k + ')').test(format)) {
          format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
        }
      }
      return format
    },

    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        '已支付': 'success',
        '未支付': 'warning',
        '已取消': 'danger',
        '已完成': 'success',
        '进行中': 'primary',
        '已退款': 'info'
      }
      return statusMap[status] || 'info'
    },

    // 订单列表筛选查询
    handleOrderQuery() {
      this.pagination.pageNum = 1 // 重置到第一页
      this.loadOrderDetails()
    },

    // 重置订单筛选条件
    resetOrderQuery() {
      this.orderQueryParams = {
        userName: '',
        orderTimeRange: [],
        minTotalAmount: '',
        maxTotalAmount: '',
        minPaymentAmount: '',
        maxPaymentAmount: '',
        paymentStatus: ''
      }
      this.pagination.pageNum = 1
      this.loadOrderDetails()
    },

    // 获取表格合计数据
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }

        const values = data.map(item => {
          if (column.property === 'total_amount' || column.property === 'payment_amount') {
            return Number(item[column.property]) || 0
          }
          if (column.property === 'product_quantity') {
            return Number(item[column.property]) || 0
          }
          return 0
        })

        if (column.property === 'total_amount') {
          const sum = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = '¥' + this.formatNumber(sum.toFixed(2))
        } else if (column.property === 'payment_amount') {
          const sum = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = '¥' + this.formatNumber(sum.toFixed(2))
        } else if (column.property === 'product_quantity') {
          const sum = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = sum
        } else if (column.property === 'user_name') {
          sums[index] = `共${data.length}条记录`
        } else {
          sums[index] = ''
        }
      })

      return sums
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb20 {
  margin-bottom: 20px;
}

/* 核心指标卡片样式 */
.metric-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.metric-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.metric-icon {
  margin-right: 16px;
}

.metric-icon i {
  font-size: 32px;
}

.metric-content {
  flex: 1;
}

.metric-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.metric-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.metric-trend {
  font-size: 12px;
}

.trend-up {
  color: #67C23A;
}

.trend-down {
  color: #F56C6C;
}

/* 卡片样式 */
.box-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.box-card .el-card__header {
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

/* 表格样式优化 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background: #f8f9fa;
  color: #333;
  font-weight: 600;
}

.el-table td {
  border-bottom: 1px solid #f0f0f0;
}

.el-table--border::after,
.el-table--group::after,
.el-table::before {
  background-color: #e9ecef;
}

/* 分页样式 */
.el-pagination {
  margin-top: 20px;
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .metric-card {
    margin-bottom: 16px;
  }

  .metric-value {
    font-size: 20px;
  }

  .metric-icon i {
    font-size: 24px;
  }
}

/* 图表容器样式 */
.chart-container {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 加载状态样式 */
.el-loading-mask {
  border-radius: 8px;
}

/* 按钮样式优化 */
.el-button--mini {
  padding: 7px 15px;
  font-size: 12px;
  border-radius: 4px;
}

/* 表单样式 */
.el-form--inline .el-form-item {
  margin-right: 20px;
  margin-bottom: 15px;
}

/* 标签样式 */
.el-tag--mini {
  height: 20px;
  line-height: 18px;
  font-size: 11px;
  padding: 0 5px;
}

/* 日期选择器样式 */
.el-date-editor {
  width: 240px;
}

/* 单选按钮组样式 */
.el-radio-group .el-radio-button__inner {
  padding: 8px 12px;
  font-size: 12px;
}
</style>
